package com.example.words;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SearchView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import java.util.List;


/**
 * A simple {@link Fragment} subclass.
 */
public class WordsFragment extends Fragment {
    private WordViewModel wordViewModel;
    private RecyclerView recyclerView;
    private MyAdapter myAdapter1,myAdapter2;
    private LiveData<List<Word>> filteredWords;

    private final static String VIEW_TYPE_SHP = "view_type_shp";
    private final static String IS_USING_CARD_VIEW = "is_using_card_view";

    private List<Word> allWords;
    //判断是否删除的标识
    private boolean undoAction;

    //边线
    private DividerItemDecoration dividerItemDecoration;


    public WordsFragment() {
        // Required empty public constructor
        //默认显示新增加的菜单项
        setHasOptionsMenu(true);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_words, container, false);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        wordViewModel = new ViewModelProvider(requireActivity()).get(WordViewModel.class);
        recyclerView = requireActivity().findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireActivity()));
        myAdapter1 = new MyAdapter(false,wordViewModel);
        myAdapter2 = new MyAdapter(true,wordViewModel);

        //当切换动画结束后会刷新序列号，手动刷新序列号
        recyclerView.setItemAnimator(new DefaultItemAnimator(){
            @Override
            public void onAnimationFinished(@NonNull RecyclerView.ViewHolder viewHolder) {
                super.onAnimationFinished(viewHolder);
                LinearLayoutManager linearLayoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if(linearLayoutManager != null){
                    int firstPotion = linearLayoutManager.findFirstVisibleItemPosition();
                    int lastPotion = linearLayoutManager.findLastVisibleItemPosition();
                    for(int i= firstPotion; i<= lastPotion;i++){
                        MyAdapter.MyViewHolder holder = (MyAdapter.MyViewHolder) recyclerView.findViewHolderForAdapterPosition(i);
                        if(holder != null){
                            holder.textViewNumber.setText(String.valueOf(i + 1));
                        }
                    }
                }
            }
        });
        //recyclerView.setAdapter(myAdapter1);
        //记住选择的视图
        SharedPreferences shp = requireActivity().getSharedPreferences(VIEW_TYPE_SHP,Context.MODE_PRIVATE);
        boolean viewType = shp.getBoolean(IS_USING_CARD_VIEW,false);
        //边线效果
        dividerItemDecoration = new DividerItemDecoration(requireActivity(),DividerItemDecoration.VERTICAL);
        if(viewType){
            recyclerView.setAdapter(myAdapter2);
        }else {
            recyclerView.setAdapter(myAdapter1);
           //非卡片就添加边线
            recyclerView.addItemDecoration(dividerItemDecoration);
        }

        filteredWords = wordViewModel.getAllWordsLive();
        //requireActivity()修改为getViewLifecycleOwner()，不然会出现在搜索单词后，再关闭中文释义会出现问题
//        filteredWords.observe(requireActivity(), new Observer<List<Word>>() {
        filteredWords.observe(getViewLifecycleOwner(), new Observer<List<Word>>() {
            @Override
            public void onChanged(List<Word> words) {
                int temp = myAdapter1.getItemCount();
//                myAdapter1.setAllWords(words);
//                myAdapter2.setAllWords(words);
                allWords = words;
                if(temp != words.size()){
                    //以下代码会刷新整个数据，增加内存开销,切换效果不平滑
                    //myAdapter1.notifyDataSetChanged();
                    //myAdapter2.notifyDataSetChanged();

                    //改进方法，以下代码根据提交的数据列表会在后台进行差异化比较根据比对结果，来刷新界面
                    //不会刷新整个界面，增加数据切换的平滑效果
                    //只有当增加单词时且不撤销删除时才添加滚动效果
                    if(temp < words.size() && !undoAction){
                        recyclerView.smoothScrollBy(0,-400);//当单词填满屏幕后出现滚动效果
                    }
                    undoAction = false;
                    myAdapter1.submitList(words);
                    myAdapter2.submitList(words);
                }
            }
        });

        //滑动删除
        /**
         * 其中dragDirs支持拖拽，设置0就表示禁止拖拽
         * swipeDirs支持滑动
         */
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN,ItemTouchHelper.START | ItemTouchHelper.END) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                Word wordFrom = allWords.get(viewHolder.getAdapterPosition());
                Word wordTo = allWords.get(target.getAdapterPosition());
                int idTemp = wordFrom.getId();
                wordFrom.setId(wordTo.getId());
                wordTo.setId(idTemp);
                wordViewModel.updateWords(wordFrom,wordTo);//添加确拖动定键，在改键中完成对数据库的操作,不然有bug
                myAdapter1.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());
                myAdapter2.notifyItemMoved(viewHolder.getAdapterPosition(),target.getAdapterPosition());
                return false;
            }



            //滑动删除选定的word
            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                //get可能为空，livedata为异步处理数据
                //Word wordToDelete = filteredWords.getValue().get(viewHolder.getAdapterPosition());
                final Word wordToDelete = allWords.get(viewHolder.getAdapterPosition());
                Snackbar.make(requireActivity().findViewById(R.id.wordFragmentView),"删除了一个单词",Snackbar.LENGTH_SHORT)
                        .setAction("撤销", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                undoAction = true;
                                wordViewModel.insertWords(wordToDelete);
                            }
                        }).show();

                wordViewModel.deleteWords(wordToDelete);
            }
        }).attachToRecyclerView(recyclerView);

        FloatingActionButton floatingActionButton = requireActivity().findViewById(R.id.floatingActionButton);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                NavController navController = Navigation.findNavController(view);
                navController.navigate(R.id.action_wordsFragment_to_addFragment);
            }
        });
    }

    //加载新创建标题中菜单项和搜索框，响应搜索框事件
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.main_menu,menu);
        //防止点击search（放大镜）时把标题words挤出去
        SearchView searchView = (SearchView) menu.findItem(R.id.app_bar_search).getActionView();
        searchView.setMaxWidth(1000);

        //设置searchView的监听器
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {
                String pattern = s.trim();
                //移除filteredWords在onActivityCreated中创建的观察，不然会发生碰撞
                //requireActivity()修改为getViewLifecycleOwner()，不然会出现在搜索单词后，在关闭中文释义会出现问题
//                filteredWords.removeObservers(requireActivity());
                filteredWords.removeObservers(getViewLifecycleOwner());
                filteredWords = wordViewModel.findWordWithPatten(pattern);
//                filteredWords.observe(requireActivity(), new Observer<List<Word>>() {
                filteredWords.observe(getViewLifecycleOwner(), new Observer<List<Word>>() {

                    @Override
                    public void onChanged(List<Word> words) {
                        int temp = myAdapter1.getItemCount();
//                        myAdapter1.setAllWords(words);
//                        myAdapter2.setAllWords(words);
                        allWords = words;
                        if(temp != words.size()){
//                            myAdapter1.notifyDataSetChanged();
//                            myAdapter2.notifyDataSetChanged();

                            //改进方法，以下代码根据提交的数据列表会在后台进行差异化比较根据比对结果，来刷新界面
                            //不会刷新整个界面，增加数据切换的平滑效果
                            myAdapter1.submitList(words);
                            myAdapter2.submitList(words);
                        }
                    }
                });

                return true;//不需要将事件继续传递就返回true
            }
        });
    }

   //响应标题菜单中菜单项的点击事件
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.clearData:
                AlertDialog.Builder builder = new AlertDialog.Builder(requireActivity());
                builder.setTitle("清空数据");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        wordViewModel.deleteAllWords();
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                builder.create();
                builder.show();
                break;
            case R.id.switchvVewType:
                SharedPreferences shp = requireActivity().getSharedPreferences(VIEW_TYPE_SHP,Context.MODE_PRIVATE);
                boolean viewType = shp.getBoolean(IS_USING_CARD_VIEW,false);
                SharedPreferences.Editor editor = shp.edit();
                if(viewType)
                {
                    recyclerView.setAdapter(myAdapter1);
                    //非卡片添加边线
                    recyclerView.addItemDecoration(dividerItemDecoration);
                    editor.putBoolean(IS_USING_CARD_VIEW,false);
                }else {
                    recyclerView.setAdapter(myAdapter2);
                    //卡片删除边线
                    recyclerView.removeItemDecoration(dividerItemDecoration);
                    editor.putBoolean(IS_USING_CARD_VIEW,true);
                }
                editor.apply();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}
